package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.kuaidi100.sdk.response.ProductCategoryResp;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.model.response.IdCountResponse;
import com.ytjj.qmyx.supplychain.mapper.ProductAttributeMapper;
import com.ytjj.qmyx.supplychain.mapper.ProductAttributeRelationMapper;
import com.ytjj.qmyx.supplychain.mapper.ProductCategoryMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxProductAttribute;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductAttributeService {

    @Resource
    private ProductAttributeMapper productAttributeMapper;
    @Resource
    private ProductAttributeRelationMapper productAttributeRelationMapper;
    @Resource
    private ProductCategoryMapper productCategoryMapper;


    public CommonResult addOrEdit(YxProductAttribute request) {
        String join = StringUtils.join(request.getAttributeValueList(), ",");
        request.setAttributeValue(join);
        if (null == request.getId()){
            productAttributeMapper.insertSelective(request);
        }else {
            YxProductAttribute yxProductAttribute = productAttributeMapper.selectByPrimaryKey(request.getId());
            yxProductAttribute.setAttributeName(request.getAttributeName());
            yxProductAttribute.setTopCategoryId(request.getTopCategoryId());
            yxProductAttribute.setCategoryId(request.getCategoryId());
            yxProductAttribute.setBottomCategoryId(request.getBottomCategoryId());
            yxProductAttribute.setAttributeValue(request.getAttributeValue());
            yxProductAttribute.setAttributeExplain(request.getAttributeExplain());
            yxProductAttribute.setAttributeType(request.getAttributeType());
            yxProductAttribute.setStatus(request.getStatus());
            yxProductAttribute.setIsRequired(request.getIsRequired());
            yxProductAttribute.setInputType(request.getInputType());
            yxProductAttribute.setReviser(request.getReviser());
            yxProductAttribute.setUpdateTime(new Date());
            productAttributeMapper.updateByPrimaryKey(yxProductAttribute);
        }
        return CommonResult.success();
    }

    public CommonResult list(Integer id, String attributeName, Integer attributeType, Integer status, Integer pageNum, Integer pageSize) {
        //strings =  Arrays.asList(str.split(","));
        PageHelper.startPage(pageNum, pageSize);
        List<YxProductAttribute> list = productAttributeMapper.selectPage(id, attributeName, attributeType, status);
        if (CollectionUtils.isEmpty(list)){
            return CommonResult.success(CommonPage.restPage(new ArrayList<>()));
        }
        CommonPage page = CommonPage.restPage(list);
        //商品数量
        List<Integer> attributeIds = list.stream().map(YxProductAttribute::getId).collect(Collectors.toList());
        List<IdCountResponse> countList = productAttributeRelationMapper.selectCountByAttributeIds(attributeIds);
        //分类名称
        List<ProductCategoryResp> productCategoryResps = new ArrayList<>();
        List<Integer> collect = list.stream().filter(item ->null != item.getTopCategoryId()).map(YxProductAttribute::getTopCategoryId).collect(Collectors.toList());
        List<Integer> collect1 = list.stream().filter(item ->null != item.getCategoryId()).map(YxProductAttribute::getCategoryId).collect(Collectors.toList());
        List<Integer> collect2 = list.stream().filter(item ->null != item.getBottomCategoryId()).map(YxProductAttribute::getBottomCategoryId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect1)) collect.addAll(collect1);
        if (!CollectionUtils.isEmpty(collect2)) collect.addAll(collect2);
        if (!CollectionUtils.isEmpty(collect)){
            List<Integer> categoryIds = collect.stream().distinct().collect(Collectors.toList());
            productCategoryResps = productCategoryMapper.selectCategoryByIds(categoryIds);
        }
        List<ProductCategoryResp> finalProductCategoryResps = productCategoryResps;

        page.setList(list.stream().map(item ->{
            item.setProductNum(0);
            //关联的商品数量
            if (!CollectionUtils.isEmpty(countList)){
                List<IdCountResponse> countResponses = countList.stream().filter(count -> item.getId().equals(count.getId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(countResponses)) item.setProductNum(countResponses.get(0).getCountNum());
            }
            //转换属性值
            if (StringUtils.isNotBlank(item.getAttributeValue())) item.setAttributeValueList(Arrays.asList(item.getAttributeValue().split(",")));
            //类目名称
            if (!CollectionUtils.isEmpty(finalProductCategoryResps)){
                if (null != item.getTopCategoryId()){
                    List<ProductCategoryResp> category = finalProductCategoryResps.stream().filter(resp -> resp.getId().equals(item.getTopCategoryId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(category)) item.setTopCategoryName(category.get(0).getTitle());
                }
                if (null != item.getCategoryId()){
                    List<ProductCategoryResp> category = finalProductCategoryResps.stream().filter(resp -> resp.getId().equals(item.getCategoryId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(category)) item.setCategoryName(category.get(0).getTitle());
                }
                if (null != item.getBottomCategoryId()){
                    List<ProductCategoryResp> category = finalProductCategoryResps.stream().filter(resp -> resp.getId().equals(item.getBottomCategoryId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(category)) item.setBottomCategoryName(category.get(0).getTitle());
                }

            }
            return item;
        }).collect(Collectors.toList()));
        return CommonResult.success(page);
    }

    public CommonResult delete(Integer id) {
        int i = productAttributeMapper.deleteByPrimaryKey(id);
        return i > 0 ? CommonResult.success() : CommonResult.failed();
    }

    public CommonResult attributeByCategory(Integer topCategoryId, Integer categoryId, Integer bottomCategoryId) {
        List<YxProductAttribute> list = new ArrayList<>();
        Example example = new Example(YxProductAttribute.class);
        example.createCriteria().andEqualTo("topCategoryId",topCategoryId).andEqualTo("status",1).andEqualTo("isDelete",0).andIsNull("categoryId").andIsNull("bottomCategoryId");
        List<YxProductAttribute> list1 = productAttributeMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list1)) list.addAll(list1);
        if (null != categoryId){
            example.clear();
            example.createCriteria().andEqualTo("topCategoryId",topCategoryId).andEqualTo("status",1).andEqualTo("isDelete",0).andEqualTo("categoryId",categoryId).andIsNull("bottomCategoryId");
            List<YxProductAttribute> list2 = productAttributeMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(list2)) list.addAll(list2);
        }
        if (null != categoryId && null != bottomCategoryId){
            example.clear();
            example.createCriteria().andEqualTo("topCategoryId",topCategoryId).andEqualTo("status",1).andEqualTo("isDelete",0).andEqualTo("categoryId",categoryId).andEqualTo("bottomCategoryId",bottomCategoryId);
            List<YxProductAttribute> list2 = productAttributeMapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(list2)) list.addAll(list2);
        }
        if (CollectionUtils.isEmpty(list)) return CommonResult.success(new ArrayList<>());
        list = list.stream().map(item ->{
            if (StringUtils.isNotBlank(item.getAttributeValue())) item.setAttributeValueList(Arrays.asList(item.getAttributeValue().split(",")));
            return item;
        }).sorted(Comparator.comparing(YxProductAttribute::getInputType)).collect(Collectors.toList());

        return CommonResult.success(list);
    }
}
